from flask_restful import Resource,reqparse

from .. import models,db
from . import order_api
class Orders(Resource):
    def get(self):
        '''获取订单列表'''
        try:
            parser = reqparse.RequestParser()
            #添加参数
            parser.add_argument('name',type=str,location='args')
            args = parser.parse_args()
            name = args.get('name')
            if name:
                order_list = models.Order.query.filter(models.Order.user.has(models.User.name.like('%'+name+'%'))).all()
            else:
                order_list = models.Order.query.all()
            return {'status':200,'msg':'获取订单成功','data':[order.to_dict() for order in order_list]}

        except Exception as e:
            return {'status':500,'msg':'获取订单失败'}

order_api.add_resource(Orders,'/orders/')

class Order(Resource):
    def get(self,id):
        '''获取订单详情'''
        try:
            order = models.Order.query.get(id)
            return {'status':200,'msg':'获取订单详情成功','data':order.to_dict()}
        except Exception as e:
            return {'status':500,'msg':'获取订单详情失败'}

order_api.add_resource(Order,'/order/<int:id>/')


class Expresses(Resource):
    def get(self,id):
        '''获取订单物流信息'''
        try:
            express_list = models.Express.query.filter(models.Express.oid==id).order_by(models.Express.update_time.desc()).all()
            return {'status':200,'msg':'获取订单物流信息成功','data':[express.to_dict() for express in express_list]}
        except Exception as e:
            return {'status':500,'msg':'获取订单物流信息失败'}

order_api.add_resource(Expresses,'/expresses/<int:id>/')
